﻿using System;
using System.Collections.Generic;
using System.IO;
using NTTDATA.BEENChina.CaseMonitor.Base;

namespace NTTDATA.BEENChina.CaseMonitor.ServerChecker
{
    public class RunningChecker : BaseChecker
    {
        private const String ConfigFile= "RunningCheckerConfig.xml";
        private static object lockobj = new object();
        private RunningChecker(){}

        public static RunningChecker GetInstance()
        {
            
            System.Threading.Thread.Sleep(1000);

            lock (lockobj)
            {
                if (runningChecker == null)
                    runningChecker = new RunningChecker();

                return runningChecker;
            }
           
        }

        private static RunningChecker runningChecker;


        public int MonitorSpan
        {
            get;
            set;
        }
        

        private DateTime checkTime;


        private List<ServerChecker> checker = null;

        public List<Server> Check()
        {   
            try
            {
                checkTime = DateTime.Now;

                if (checker ==null)
                {
                    onProcessMessage("Instance RunningChecker");
                    checker = getObject();
                }

                List<Server> notes = CheckRunning(checker);

                onProcessMessage("Return runningChecker over");
                if (notes.Count>0)
                {
                    onProcessMessage("Return runningChecker result");
                }

                return notes;
            }
            catch (Exception exp)
            {
                Log.Console.Error("RunningChecker", exp);
            }
            return null;
        }

        private List<ServerChecker> getObject()
        {
            onProcessMessage("load config file");

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFile);

            if (!System.IO.File.Exists(filePath))
            {
                throw new FileNotFoundException(filePath);
            }

            onProcessMessage("Deserialize xml file");
            using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
            {
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(List<ServerChecker>));
                List<ServerChecker> obj = (List<ServerChecker>)xs.Deserialize(reader); 
                reader.Close();
                return obj;
            }
        }

        public static void SetObject(string fileName, Object xmlobj)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory;
            //fileName = @"RunningCheckerConfig.xml";

            fileName = Path.Combine(filePath, fileName);
            using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //得到被序列化的类型
                Type type = xmlobj.GetType();
                System.Xml.Serialization.XmlSerializer sz = new System.Xml.Serialization.XmlSerializer(type);
                //开始序列化
                sz.Serialize(stream, xmlobj);
            }
        }

        private List<Server> CheckRunning(List<ServerChecker> checkerlist)
        {
            if (checkerlist == null)
            {
                throw new ArgumentNullException("checkRunning,parameter:checkerlist");
            }

            List<Server> ret = new List<Server>();
            foreach (ServerChecker checker in checkerlist)
            {
                checkServerRunning(checker, ret);
            }

            return ret;
        }

        private List<Server> checkServerRunning(ServerChecker checker, List<Server> ret)
        {
            if (checker == null)
            {
                throw new ArgumentNullException("checkServerRunning,parameter:checker");
            }
            if (ret == null)
            {
                throw new ArgumentNullException("checkServerRunning,parameter:ret");
            }

           
            foreach (Server server in checker.NoteList)
            {
                ServerState serverState = server.IsRunning();

                if ( serverState != ServerState.Running)
               {
                   ret.Add(server);
               }

                onProcessMessage(string.Format("Server:{0} {1}", server.Name, serverState));
            }
            return  ret;
        }

       
        
        
        
    }
}